//Fetch all the links and convert it into a js array.
var links = [].slice.apply(document.getElementsByTagName('a'));

//Restore them back into the links list
links = links.map(function(element) {
	var href = element.href;
  
	//Eliminate some garbage
	var hashIndex = href.indexOf('#');
	if (hashIndex >= 0) {
		href = href.substr(0, hashIndex);
	}
	return href;
});

//Sort the list in alphabetical order
links.sort();

// Remove duplicates and invalid URLs.
var badPrefix = 'javascript';
for (var i = 0; i < links.length;) {
	
	//Find duplicates, null, invalid input
	if (((i > 0) && (links[i] == links[i - 1])) || (links[i] == '') || 
			(badPrefix == links[i].toLowerCase().substr(0, badPrefix.length))) {
		
		//Remove unwanted ones
		links.splice(i, 1);
	}

	//If we remove an element, we don't need to increment the iterator
	else i++;
}

//Send the request back to the extension
chrome.extension.sendRequest(links);
